/*
 * DayConsumeFrame.java
 *
 * Created on __DATE__, __TIME__
 */

package com.insigma.yanwenlong.bookkeeping.gui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;

import com.insigma.yanwenlong.bookkeeping.pojo.Account;
import com.insigma.yanwenlong.bookkeeping.pojo.Category;
import com.insigma.yanwenlong.bookkeeping.pojo.DayConsumeCondition;
import com.insigma.yanwenlong.bookkeeping.pojo.Member;
import com.insigma.yanwenlong.bookkeeping.pojo.vo.DetailVo;
import com.insigma.yanwenlong.bookkeeping.service.AccountService;
import com.insigma.yanwenlong.bookkeeping.service.AccountServiceImpl;
import com.insigma.yanwenlong.bookkeeping.service.CategoryService;
import com.insigma.yanwenlong.bookkeeping.service.CategoryServiceImpl;
import com.insigma.yanwenlong.bookkeeping.service.DetailService;
import com.insigma.yanwenlong.bookkeeping.service.DetailServiceImpl;
import com.insigma.yanwenlong.bookkeeping.service.MemberService;
import com.insigma.yanwenlong.bookkeeping.service.MemberServiceImpl;

/**
 *
 * @author  __USER__
 */
public class DayConsumeFrame extends javax.swing.JFrame {
	private AccountService accountService = new AccountServiceImpl();
	private MemberService memberService = new MemberServiceImpl();
	private DetailService detailService = new DetailServiceImpl();
	private CategoryService categoryService = new CategoryServiceImpl();
	DefaultTableModel dtmIncome;
	DefaultTableModel dtmOutcome;

	/** Creates new form DayConsumeFrame */
	public DayConsumeFrame() {
		this.setTitle("日常收支表");
		initComponents();
		setLocationRelativeTo(null);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		//初始化账户
		initAccount();
		//初始化家庭成员
		initMember();
		//初始化收入
		initIncome();
	}

	private void initIncome() {
		Category category = null;
		double income = 0;
		double outcome = 0;
		try {
			List<DetailVo> detailVos = detailService.findDetails();
			dtmIncome = (DefaultTableModel) tblIncome.getModel();
			dtmOutcome = (DefaultTableModel) tblOutcome.getModel();
			for (DetailVo detailVo : detailVos) {
				int categoryId = detailVo.getCategoryId();
				category = categoryService.findDirectionIdById(categoryId);
				if (category.getDirectionId() == 1) {
					dtmOutcome.addRow(new Object[] {
							detailVo.getCategoryName(),
							detailVo.getHappenMoney() });
					outcome += detailVo.getHappenMoney();
				} else {
					dtmIncome.addRow(new Object[] { detailVo.getCategoryName(),
							detailVo.getHappenMoney() });
					income += detailVo.getHappenMoney();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		lblTotal.setText(String.valueOf(income - outcome));
	}

	private void initMember() {
		try {
			List<Member> members = memberService.findallMembers();
			DefaultComboBoxModel dcbm = (DefaultComboBoxModel) cobMember
					.getModel();
			for (Member member : members) {
				dcbm.addElement(member);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	private void initAccount() {
		try {
			List<Account> accounts = accountService.findaAccounts();
			DefaultComboBoxModel dcbm = (DefaultComboBoxModel) cobAccount
					.getModel();
			for (Account account : accounts) {
				dcbm.addElement(account);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	//GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		cobAccount = new javax.swing.JComboBox();
		jLabel2 = new javax.swing.JLabel();
		cobTime = new javax.swing.JComboBox();
		jLabel3 = new javax.swing.JLabel();
		jtfBeginTime = new javax.swing.JTextField();
		jLabel4 = new javax.swing.JLabel();
		jtfEndTime = new javax.swing.JTextField();
		jLabel5 = new javax.swing.JLabel();
		cobMember = new javax.swing.JComboBox();
		jLabel6 = new javax.swing.JLabel();
		spnBeginMoney = new javax.swing.JSpinner();
		spnEndMoney = new javax.swing.JSpinner();
		jLabel7 = new javax.swing.JLabel();
		btnSearch = new javax.swing.JButton();
		btnExport = new javax.swing.JButton();
		jLabel8 = new javax.swing.JLabel();
		jScrollPane1 = new javax.swing.JScrollPane();
		tblIncome = new javax.swing.JTable();
		jLabel9 = new javax.swing.JLabel();
		jScrollPane2 = new javax.swing.JScrollPane();
		tblOutcome = new javax.swing.JTable();
		jLabel10 = new javax.swing.JLabel();
		lblTotal = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jLabel1.setText("\u8d26\u6237");

		cobAccount.setModel(new javax.swing.DefaultComboBoxModel(
				new String[] { "请选择" }));

		jLabel2.setText("\u65f6\u95f4");

		cobTime.setModel(new javax.swing.DefaultComboBoxModel(
				new String[] { "自定义" }));

		jLabel3.setText("\u4ece");

		jLabel4.setText("\u5230");

		jLabel5.setText("\u5bb6\u5ead\u6210\u5458");

		cobMember.setModel(new javax.swing.DefaultComboBoxModel(
				new String[] { "请选择" }));

		jLabel6.setText("\u91d1\u989d\u4ece");

		spnBeginMoney.setModel(new javax.swing.SpinnerNumberModel(Double
				.valueOf(0.0d), Double.valueOf(0.0d), null, Double
				.valueOf(100.0d)));

		spnEndMoney.setModel(new javax.swing.SpinnerNumberModel(Double
				.valueOf(0.0d), Double.valueOf(0.0d), null, Double
				.valueOf(200.0d)));

		jLabel7.setText("\u5230");

		btnSearch.setText("\u67e5\u8be2");
		btnSearch.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnSearchActionPerformed(evt);
			}
		});

		btnExport.setText("\u5bfc\u51fa");
		btnExport.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnExportActionPerformed(evt);
			}
		});

		jLabel8.setText("\u6536\u5165\uff1a");

		tblIncome.setModel(new javax.swing.table.DefaultTableModel(
				new Object[][] {

				}, new String[] { "类别", "金额" }) {
			boolean[] canEdit = new boolean[] { false, false };

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		jScrollPane1.setViewportView(tblIncome);

		jLabel9.setText("\u652f\u51fa\uff1a");

		tblOutcome.setModel(new javax.swing.table.DefaultTableModel(
				new Object[][] {

				}, new String[] { "类别", "金额" }) {
			boolean[] canEdit = new boolean[] { false, false };

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		jScrollPane2.setViewportView(tblOutcome);

		jLabel10.setText("\u603b\u5408\u8ba1\uff1a");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																jScrollPane1,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																485,
																Short.MAX_VALUE)
														.addComponent(
																jLabel8,
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING,
																								false)
																						.addGroup(
																								layout
																										.createSequentialGroup()
																										.addComponent(
																												jLabel1,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												45,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												cobAccount,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												79,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										.addComponent(
																												jLabel2)
																										.addGap(
																												18,
																												18,
																												18)
																										.addComponent(
																												cobTime,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												71,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												jLabel3))
																						.addGroup(
																								layout
																										.createSequentialGroup()
																										.addComponent(
																												jLabel5)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										.addComponent(
																												cobMember,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												80,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										.addComponent(
																												jLabel6)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												spnBeginMoney)))
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addGroup(
																								layout
																										.createSequentialGroup()
																										.addGap(
																												6,
																												6,
																												6)
																										.addComponent(
																												jLabel7)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												spnEndMoney,
																												javax.swing.GroupLayout.DEFAULT_SIZE,
																												70,
																												Short.MAX_VALUE)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												btnSearch)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												btnExport))
																						.addGroup(
																								layout
																										.createSequentialGroup()
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										.addComponent(
																												jtfBeginTime,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												90,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										.addComponent(
																												jLabel4)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																										.addComponent(
																												jtfEndTime,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												92,
																												javax.swing.GroupLayout.PREFERRED_SIZE))))
														.addComponent(
																jLabel9,
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																jScrollPane2,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																485,
																Short.MAX_VALUE)
														.addGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																layout
																		.createSequentialGroup()
																		.addComponent(
																				jLabel10)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				lblTotal,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				101,
																				javax.swing.GroupLayout.PREFERRED_SIZE)))
										.addContainerGap()));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel1)
														.addComponent(
																cobAccount,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(jLabel2)
														.addComponent(
																cobTime,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(jLabel3)
														.addComponent(jLabel4)
														.addComponent(
																jtfEndTime,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																jtfBeginTime,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(18, 18, 18)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel5)
														.addComponent(
																cobMember,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(jLabel6)
														.addComponent(
																spnBeginMoney,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(jLabel7)
														.addComponent(
																spnEndMoney,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(btnSearch)
														.addComponent(btnExport))
										.addGap(18, 18, 18)
										.addComponent(jLabel8)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jScrollPane1,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												96,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(34, 34, 34)
										.addComponent(jLabel9)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jScrollPane2,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												120,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel10)
														.addComponent(
																lblTotal,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																15,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(23, 23, 23)));

		pack();
	}// </editor-fold>
	//GEN-END:initComponents

	//点击导出，将查询到结果存放到文件中
	private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {
		int row = dtmIncome.getRowCount();
		int column = dtmIncome.getColumnCount();
		int row1 = dtmOutcome.getRowCount();
		int column1 = dtmOutcome.getColumnCount();
		String[] information = new String[row];
		String[] information1 = new String[row1];
		for (int i = 0; i < row; i++) {
			information[i] = "";
			for (int j = 0; j < column; j++) {
				information[i] += dtmIncome.getValueAt(i, j) + "\t";
			}
			information[i] += "\n";
		}

		for (int i = 0; i < row1; i++) {
			information1[i] = "";
			for (int j = 0; j < column1; j++) {
				information1[i] += dtmOutcome.getValueAt(i, j) + "\t";
			}
			information1[i] += "\n";
		}

		File file = new File("D:/日常收支.txt");
		OutputStreamWriter osw = null;
		String s = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(file));
			for (int index = 0; index < row; index++) {
				try {
					if (index == 0) {
						osw.write("收入：" + "\r\n");
					}
					s = information[index].replace("\n", "\r\n");
					osw.write(s);
					osw.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			for (int index1 = 0; index1 < row1; index1++) {
				try {
					if (index1 == 0) {
						osw.write("\r\n" + "支出：" + "\r\n");
					}
					s = information1[index1].replace("\n", "\r\n");
					osw.write(s);
					osw.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				osw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	//点击查询，显示查询结果
	private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
		int accountId = -1;
		if (cobAccount.getSelectedItem() instanceof Account) {
			Account account = (Account) cobAccount.getSelectedItem();
			accountId = account.getId();
		}

		int memberId = -1;
		if (cobMember.getSelectedItem() instanceof Member) {
			Member member = (Member) cobMember.getSelectedItem();
			memberId = member.getId();
		}

		String starTime = jtfBeginTime.getText();
		String endTime = jtfEndTime.getText();

		double beginMoney = (Double) spnBeginMoney.getValue();
		double endMoney = (Double) spnEndMoney.getValue();

		DayConsumeCondition dcc = new DayConsumeCondition();
		dcc.setAccountId(accountId);
		dcc.setBeginTime(starTime);
		dcc.setEndTime(endTime);
		dcc.setMemberId(memberId);
		dcc.setStarMoney(beginMoney);
		dcc.setEndMoney(endMoney);

		initDayConsume(dcc);
	}

	private void initDayConsume(DayConsumeCondition dcc) {
		Category category = null;
		double income = 0;
		double outcome = 0;
		try {
			List<DayConsumeCondition> dccs = detailService
					.findDayConsumeConditions(dcc);
			dtmIncome = (DefaultTableModel) tblIncome.getModel();
			dtmIncome.setRowCount(0);
			dtmOutcome = (DefaultTableModel) tblOutcome.getModel();
			dtmOutcome.setRowCount(0);
			for (DayConsumeCondition dcc2 : dccs) {
				int categoryId = dcc2.getCategoryId();
				category = categoryService.findDirectionIdById(categoryId);
				if (category.getDirectionId() == 1) {
					dtmOutcome
							.addRow(new Object[] { category.getCategoryName(),
									dcc2.getHappenMoney() });
					outcome += dcc2.getHappenMoney();
				} else {
					dtmIncome.addRow(new Object[] { category.getCategoryName(),
							dcc2.getHappenMoney() });
					income += dcc2.getHappenMoney();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		lblTotal.setText(String.valueOf(income - outcome));

	}

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new DayConsumeFrame().setVisible(true);
			}
		});
	}

	//GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton btnExport;
	private javax.swing.JButton btnSearch;
	private javax.swing.JComboBox cobAccount;
	private javax.swing.JComboBox cobMember;
	private javax.swing.JComboBox cobTime;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel10;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JLabel jLabel6;
	private javax.swing.JLabel jLabel7;
	private javax.swing.JLabel jLabel8;
	private javax.swing.JLabel jLabel9;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JTextField jtfBeginTime;
	private javax.swing.JTextField jtfEndTime;
	private javax.swing.JLabel lblTotal;
	private javax.swing.JSpinner spnBeginMoney;
	private javax.swing.JSpinner spnEndMoney;
	private javax.swing.JTable tblIncome;
	private javax.swing.JTable tblOutcome;
	// End of variables declaration//GEN-END:variables

}